package com.txby.platformApi.component.web;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ArithSolve;
import com.jck.tools.ChkUtil;
import com.txby.pf.common.annotation.SysLog;
import com.txby.pf.common.utils.Constant;
import com.txby.pf.common.utils.PageUtils;
import com.txby.pf.common.utils.Query;
import com.txby.pf.common.utils.R;
import com.txby.pf.common.validator.ValidatorUtils;
import com.txby.pf.common.validator.group.AddGroup;
import com.txby.pf.common.validator.group.UpdateGroup;
import com.txby.platformApi.component.service.PayOrderRefundService;
import com.txby.platformCore.entity.ProductDeviceInit;
import com.txby.platformCore.entity.ProductDeviceInitLot;
import com.txby.platformCore.entity.TxbySysApiUser;

/**
 * 商城订单退款管理
 */
@RestController
@RequestMapping("/spo/orderRefund")
public class ShopOrderRefundController  extends CommonController {
	@Resource
	private PayOrderRefundService porf;
	
	/**
	 * 所有列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("spo:orderRefund:list")
	public R list(@RequestParam Map<String, Object> params){
//		数据隔离
		String join="";
		
		String fsql="";
		
		
	/*	String sql="SELECT oge.id_ ogeId,oge.updateTime updateTime,sto.outTradeNo,go.outOrderNo,sp.name spName,g.name gName,gt.goodsTypeName gTypeName,oge.content content,oge.level,oge.isVisitor,oge.sickId FROM t_txby_sp_ordersGoodsEvaluation oge INNER JOIN  t_txby_sp_goodsOrders go INNER JOIN t_txby_sp_shopsThirdPayOrderRelation stor INNER JOIN  t_txby_sp_shopsThirdPayOrder sto on oge.ordersId=go.id_ and go.id_=stor.ordersId and stor.shopsThirdPayOrderId=sto.id_ "
				+ " INNER JOIN t_txby_sp_shops sp on  oge.shopsId=sp.id_  INNER JOIN  sys_dept d on d.dept_id=sp.deptId INNER JOIN  t_txby_sp_goodsType gt   INNER JOIN  t_txby_sp_baseGoods g on g.id_=oge.goodsId and gt.id_=oge.goodsTypeId  and g.goodsTypeId =gt.id_   " ;*/
		String sql="SELECT stpo.collectionMethod ,stgr.refundFee,stgr.refundStatus,stgr.createTime,stgr.updateTime,go.ordersStatus,gor.goodsTypeId,gor.goodsName,go.id_ ordersId,go.goodsTotalMoney,go.lastTotalMoney,go.isVisitor,go.sickId,go.outOrderNo,go.receiveAddressFull,go.receiveMobileNO,go.receiveName,gor.goodsId,gor.goodsNum,gor.price,sp.name spName from t_txby_sp_goodsOrdersRelation gor INNER JOIN  t_txby_sp_goodsOrders go on go.id_=gor.ordersId INNER JOIN t_txby_sp_shopsThirdPayOrderRelation stpor INNER JOIN t_txby_sp_shopsThirdPayOrder stpo on stpor.shopsThirdPayOrderId=stpo.id_  and  stpor.ordersId=go.id_ INNER JOIN  t_txby_sp_shopsThirdGoodsRefund  stgr  on stgr.shopsThirdPayOrderId=stpo.id_ and stgr.ordersId=go.id_   INNER JOIN t_txby_sp_shops sp on sp.id_=gor.shopsId   INNER JOIN  sys_dept d on d.dept_id=sp.deptId   " ;
		if(getUserId() != Constant.SUPER_ADMIN){
//			params.put("createUserId", getUserId());
			 join=getJoinSqlBracket();
			 sql+=" and d.dept_id in "+join;
		}
		
		
		String gName=params.get("gName")==null?"":params.get("gName").toString();
		String refundStatus=params.get("refundStatus")==null?"":params.get("refundStatus").toString();
		if(!ChkUtil.isEmptyAllObject(gName)){
			if (gName.contains("%") || gName.contains("_")) {
				gName = gName.trim().replace("%", "\\%").replace("_", "\\_");
				gName = "%" + gName + "%";
				sql += " and (go.outOrderNo like #{pojo.gName} escape '\\' or  gor.goodsName like #{pojo.gName} escape '\\' )";
				params.put("gName", "%" + gName.trim() + "%");
			} else {
				gName = "%" + gName.trim() + "%";
				sql += " and (go.outOrderNo like #{pojo.gName}   or gor.goodsName like #{pojo.gName} )";
				params.put("gName", "%" + gName.trim() + "%");
			}
		}
		
		String searchSql=" and  stgr.refundStatus=0 ";
		
		if(!ChkUtil.isEmpty(refundStatus)){
			if(refundStatus.equals("-1")){
				searchSql="";
				
			}else{
				
				searchSql="  and stgr.refundStatus="+refundStatus+"  ";
				
			}
			
		}
		
		
		sql+=searchSql;
		sql += Query.getLastSortSql(params, " order by stgr.refundStatus asc,stgr.updateTime  desc");
		//查询列表数据
		PageList<Map> pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, Query.getPageBean(params), params);
		for(Map m:pl.getResultList()){
			Long sickId=new Long(m.get("sickId").toString());
			Long isVisitor=new Long( m.get("isVisitor").toString());
			
			
			Long goodsId=new Long( m.get("goodsId").toString());
			Long goodsTypeId=new Long( m.get("goodsTypeId").toString());
			
			Long ordersId=new Long( m.get("ordersId").toString());
			Long  ordersStatus=new Long( m.get("ordersStatus").toString());
			Long  refundStatusT=new Long( m.get("refundStatus").toString());
			String refundStatusText="";
			if(refundStatusT==0){
				refundStatusText="待退款";
			}else if(refundStatusT==2){
				refundStatusText="已退款成功";
			}else{
				refundStatusText="交易关闭";
			}
				
				
			String uName="";
			
			
		     gName="";
			String gTypeName="";
			
			String goodsTotalMoney=ArithSolve.formatDoubleScaleFiveString((double) m.get("goodsTotalMoney"), 2);
			String price=ArithSolve.formatDoubleScaleFiveString((double) m.get("price"), 2);
			String refundFee=ArithSolve.formatDoubleScaleFiveString((double) m.get("refundFee"), 2);
			
			m.put("goodsTotalMoney", goodsTotalMoney);
			m.put("price", price);
			m.put("refundFee", refundFee);
			m.put("refundStatusText", refundStatusText);
			
			 
			if (isVisitor == 1) {
				sql = "SELECT CONCAT(u.name, '*', u.mobileNO) uName from  t_txby_sp_visitorUser u WHERE u.id_="+sickId+"";
			    Map userData= (Map) this.mBaseDao.findBySqlUniqueObject(sql, null, null);
			    uName=userData.get("uName").toString();
			} else {
				sql = "SELECT CONCAT(sdi.sickName, '*', sdi.mobileNO) uName from  t_txby_sickDetailInfo sdi WHERE sdi.id_="+sickId+" ";
			    Map userData= (Map) this.mBaseDao.findBySqlUniqueObject(sql, null, null);
			    uName=userData.get("uName").toString();
			}
			
			String  goodsTableName=getGoodsTableName(goodsTypeId.intValue());
		   sql="select g.name gName,gt.goodsTypeName gTypeName  from  t_txby_sp_goodsType gt,"+goodsTableName+" g   where  g.goodsTypeId =gt.id and g.id_="+goodsId+"  ";
		 
		   Map gData= (Map) this.mBaseDao.findBySqlUniqueObject(sql, null, null);
		   if(gData!=null){
			   gName=gData.get("gName").toString();
			   gTypeName=gData.get("gTypeName").toString();
		   }
		   
//		   sql=" select stpo.outTradeNo,stpo.collectionMethod,stpo.paymentTime ,stpo.payStatus ,stpo.totalMoney,stgr.refundStatus  from t_txby_sp_shopsThirdPayOrderRelation stpor INNER JOIN t_txby_sp_shopsThirdPayOrder stpo on stpor.shopsThirdPayOrderId=stpo.id_  LEFT JOIN t_txby_sp_shopsThirdGoodsRefund stgr on stgr.ordersId=stpor.ordersId and stgr.shopsThirdPayOrderId=stpo.id_ and stpor.ordersId="+ordersId+" ";
//		  
//		   Map orderTradeData= (Map) this.mBaseDao.findBySqlUniqueObject(sql, null, null);
//		   String allowRefund="n";
//		   String allowCance="n";
//		   
//		   String outTradeNo="";
//		   String paymentTime="";
//		   int collectionMethod=-1;
//	 
//		   if(orderTradeData!=null){
//			   Integer payStatus=Integer.parseInt(orderTradeData.get("payStatus").toString());
//			   if(payStatus==0&&ordersStatus==0){
//				   allowCance="y";
//				   
//			   }
//			   collectionMethod=Integer.parseInt(orderTradeData.get("collectionMethod").toString());
//			   outTradeNo=orderTradeData.get("outTradeNo").toString();
//			   paymentTime=orderTradeData.get("paymentTime")==null?"":orderTradeData.get("paymentTime").toString();
//			   if(orderTradeData.get("refundStatus")!=null){
//				   Integer refundStatus=Integer.parseInt(orderTradeData.get("refundStatus").toString());
//				   if(refundStatus!=2&&refundStatus!=3&&refundStatus!=4){
//					   allowRefund="y";
//				   }else{
//					   allowRefund="n";
//				   }
//			   }else{
//				   if(payStatus==1&&ordersStatus==1){
//					   allowRefund="y";
//				   }
//			   }
//			   
//		   }
          m.put("uName", uName);
          m.put("gName", gName);
          m.put("gTypeName", gTypeName);
			
         /* m.put("allowRefund", allowRefund);
          m.put("allowCance", allowCance);
          m.put("outTradeNo", outTradeNo);
          m.put("paymentTime", paymentTime);*/
			System.out.println(JSON.toJSON(m));
		}
		
		
		
		PageUtils pageUtil = new PageUtils(pl.getResultList(), pl.getPageBean().getTotalCount().intValue(),  pl.getPageBean().getPageSize(), pl.getPageBean().getPage());
		return R.ok().put("page", pageUtil);
	}
	
 
	
	/**
	 * 查询信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("spo:orderRefund:info")
	public R info(@PathVariable("id") Long id){
		String sql="select t.sickAreaNO sickAreaNO,t.id_ id_,t.deviceSN deviceSN,t.bedNO bedNO,t.deptId deptId,t2.name deptName,t3.name sickAreaName from  t_txby_productDeviceInit t,sys_dept t2,sys_dept t3 where t2.dept_id=t.deptId and t.sickAreaNO=t3.dept_id and t.id_="+id+"" ;
		Map pro =  (Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, null);
		return R.ok().put("pro", pro);
	}
	
	/**
	 * 保存信息
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@SysLog("保存初始化")
	@RequestMapping("/save")
	@RequiresPermissions("spo:orderRefund:save")
	public R save(@RequestBody ProductDeviceInit pd) throws IllegalAccessException, InvocationTargetException{
		ValidatorUtils.validateEntity(pd, AddGroup.class);
		String sql="select * from "+this.mBaseDao.tableName(ProductDeviceInit.class)+" where deviceSN='"+pd.getDeviceSN()+"'";
		ProductDeviceInit old=(ProductDeviceInit) this.mBaseDao.findBySqlUniqueObject(sql, ProductDeviceInit.class, null);
		if(old!=null){
	     old.setUpdater(getUserId().toString());
	     old.setUpdateTime(pd.getUpdateTime());
	     old.setBedNO(pd.getBedNO());
	     old.setSickAreaNO(pd.getSickAreaNO());
	     old.setDeptId(pd.getDeptId());
	     this.mBaseDao.updateObject(old);
	     ProductDeviceInitLot pdil=new ProductDeviceInitLot();
	     BeanUtils.copyProperties(pdil, old);
	     this.mBaseDao.updateObject(pdil);
		}else{
			sql="select * from "+this.mBaseDao.tableName(TxbySysApiUser.class)+"  where userName='"+pd.getDeviceSN()+"'";
//			db1e81c178f84c11f8dd19fa2b99c3f0
		/*	TxbySysApiUser  gau=(TxbySysApiUser) this.mBaseDao.findBySqlUniqueObject(sql, TxbySysApiUser.class, null);
			if(gau!=null) {
					gau.setPassWord(MD5Util.getMD5ofStr("db1e81c178f84c11f8dd19fa2b99c3f0", 2));
					this.mBaseDao.updateObject(gau);
					gau.setUpdateTime(new Date());
			}else{
					gau=new TxbySysApiUser();
					gau.setUserName(pd.getDeviceSN());
					gau.setPassWord(MD5Util.getMD5ofStr("db1e81c178f84c11f8dd19fa2b99c3f0", 2));
					this.mBaseDao.saveObject(gau);
				 
			}*/
			pd.setCreater(getUserId().toString());
			 pd.setUpdater(getUserId().toString());
			this.mBaseDao.saveObject(pd);
			 ProductDeviceInitLot pdil=new ProductDeviceInitLot();
		     BeanUtils.copyProperties(pdil, pd);
		     this.mBaseDao.saveObject(pd);
		}
		return R.ok();
	}
	
	/**
	 * 修改设备初始化
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@SysLog("修改设备初始化")
	@RequestMapping("/update")
	@RequiresPermissions("spo:orderRefund:update")
	public R update(@RequestBody ProductDeviceInit pd) throws IllegalAccessException, InvocationTargetException{
		ValidatorUtils.validateEntity(pd, UpdateGroup.class);
		String sql="select * from "+this.mBaseDao.tableName(ProductDeviceInit.class)+" where deviceSN='"+pd.getDeviceSN()+"'";
		ProductDeviceInit old=(ProductDeviceInit) this.mBaseDao.findBySqlUniqueObject(sql, ProductDeviceInit.class, null);
		if(old!=null){
	     old.setUpdater(getUserId().toString());
	     old.setUpdateTime(pd.getUpdateTime());
	     old.setBedNO(pd.getBedNO());
	     old.setSickAreaNO(pd.getSickAreaNO());
	     old.setDeptId(pd.getDeptId());
	     old.setSickAreaName(pd.getSickAreaName());
	     this.mBaseDao.updateObject(old);
		 ProductDeviceInitLot pdil=new ProductDeviceInitLot();
	     BeanUtils.copyProperties(pdil, old);
	     this.mBaseDao.updateObject(pdil);
		}else{
			pd.setCreater(getUserId().toString());
			 pd.setUpdater(getUserId().toString());
			this.mBaseDao.saveObject(pd);
			 ProductDeviceInitLot pdil=new ProductDeviceInitLot();
		     BeanUtils.copyProperties(pdil, pd);
		     this.mBaseDao.saveObject(pdil);
		}
		
		return R.ok();
	}
	
	/**
	 * 删除初始绑定设备
	 */
	@SysLog("订单退款操作")
	@PostMapping("/orderRefund")
	@RequiresPermissions("spo:orderRefund:refund")
	public R orderRefund(@RequestBody Long orderId){
		//更新订单状态
//		ShopsThirdGoodsRefund
//		GoodsOrders
		//保存原始退款记录
		
//		ShopsThirdPayOrderRecord
		return porf.exceuteRefund(orderId);
	}
	/**
	 * 删除初始绑定设备
	 */
	@SysLog("删除操作")
	@RequestMapping("/delete")
	@RequiresPermissions("spo:orderRefund:delete")
	public R delete(@RequestBody Long[] ids){
		for(Long id:ids){
			this.mBaseDao.executeSql(" delete from t_txby_productDeviceInit where id_="+id+"", null);
		}
		return R.ok();
	}
}
